
let moment = require('moment');
let io = {}

let refresh = true;

const m_type = {
    'jg': '加工', 'tb': '涂装半成品', 'tc': '涂装成品', 'yr': '亚克力入口', 'yc': '亚克力出口',
    'xy': '旋压', 'xy2': '旋压2', 'qm': '切帽', 'zm': '正面', 're1': '热处理1线', 're2': '热处理2线',
    'zz1': '铸造1线', 'zz2': '铸造2线', 'zz3': '铸造2线边浇', 'ng': '加工_分立', 'njg': 'F2加工_分立',
    're3': 'F2热处理'
}
const m_type_exclude = ['re1', 're2', 'zz1', 'zz2', 'zz3', 'ng', 'njg', 're3']

let db = require('./db');

const mqtt = require('mqtt');
let client = mqtt.connect({
    port: 1883,
    host: '192.168.1.100',
    protocolVersion: 4,
    keepalive: 10000
});

client.on('connect', function () {
    client.subscribe(['c/#', 'c2/#'], function (err) {
        if (!err) {
            console.log('订阅 c1 c2');
            client.publish('hello', '你好，世界');
        } else {
            console.log(err);
        }
    });

});

client.on('message', function (topic, payload, packet) {
    //console.log('消息：' + topic + ': ' + payload.toString());
    // 工厂 1 2区分
    t = topic.split('/');
    let factory = 1;
    let topic_class = t[1];
    if (t[0] == 'c2') {
        factory = 2;
    }

    save_data(topic_class, payload, factory);
    //client.end();
});

client.on('error', function (error) {
    console.log('message.js, mqtt: ' + error);
})


function save_data(topic, data, factory) {
    let obj = {};
    let temp = {};  // 发往网页
    try {
        // 转换为json
        obj = JSON.parse(data.toString());
    } catch (error) {
        console.log('错误：' + error);
        return;
    }
    // 白班、夜班判断
    let d = new Date(obj.ts);
    //console.log(obj.ts);
    // 7-20 白班， 否则夜班
    let is_day = d.getHours() >= 7 && d.getHours() < 20;

    // 交接班 刷新
    if (d.getHours() == 7) {
        if (refresh) {
            io.emit('refresh', true);
            refresh = false;
        }
    } else {
        if (!refresh) {
            refresh = true;
        }
    }

    // 区分 1个值，多个值
    let tm = moment(obj.ts);
    let obj_d = obj.d;
    if (obj_d.hasOwnProperty('tm')) {
        let obj_d_tm = obj.d.tm;
        let year = '20' + obj_d_tm[0];
        let month = obj_d_tm[1];
        let day = obj_d_tm[2];
        let hour = obj_d_tm[3];
        let min = obj_d_tm[4];
        let sec = obj_d_tm[5];
        let tm_str = `${year}-${month}-${day} ${hour}:${min}:${sec}`;

        tm = moment(tm_str, 'YYYY-M-D H:m:s');
    }
    //console.log(tm);

    if (m_type_exclude.indexOf(topic) != -1) {

        let type = m_type[topic]
        if (!type.startsWith('F')) {
            type = 'F' + factory + m_type[topic];
        }
        db.add_record(obj_d['yc'], tm, m_type[topic], factory);
        temp[type] = obj_d['yc'][0];
    } else {
        // 循环取值
        // 扔掉 tm, tm2
        for (let [k, v] of Object.entries(obj_d)) {
            if (k == 'tm' || k == 'tm2') {
                continue;
            }
            let type = m_type[k];
            if (!type.startsWith('F')) {
                type = 'F' + factory + m_type[k];
            }
            // 存入数据库
            db.add_record(obj_d[k], tm, m_type[k], factory);
            temp[type] = obj_d[k][0];
        } //for

    }
    // emmit data
    temp['factory'] = factory;
    temp['is_day'] = is_day;
    //console.log('temp:');
    //console.log(temp);
    io.emit('index_data', temp);

}

client.set_socketio = function (socket_io) {
    io = socket_io;
}

module.exports = client;
